package main

import (
	"go-shell/src/lib/check"
	"os"
	"os/exec"
	"strconv"
	"syscall"
)

func toBytes(data int) []byte {
	return []byte(strconv.Itoa(data))
}

func toInt(data []byte) int {
	result, err := strconv.Atoi(string(data))
	check.CheckErrNil(err)
	return result
}

var PID_FILE = "data/pid"

func getProcess() *os.Process {
	data, err := os.ReadFile(PID_FILE)
	check.CheckErrNil(err)
	pid := toInt(data)
	process, err := os.FindProcess(pid)
	if err != nil {
		return nil
	} else {
		if process == nil {
			return nil

		} else {
			err := process.Signal(syscall.Signal(0))
			if err.Error() == "os: process already finished" {
				println(err.Error())
				return nil
			}
			check.CheckErrNil(err)
			return process
		}
	}
}

func main() {
	cmdType := os.Args[1]
	if cmdType == "start" {
		cmd := exec.Command(os.Args[2], os.Args[3:]...)
		cmd.Start()
		os.WriteFile(PID_FILE, toBytes(cmd.Process.Pid), 0766)
		println(cmd.Process.Pid)
	} else if cmdType == "stop" {
		process := getProcess()
		if process != nil {
			err := process.Kill()
			check.CheckErrNil(err)
		}
	} else if cmdType == "status" {
		process := getProcess()
		if process != nil {
			println("running")
		} else {
			println("none")
		}
	} else {
		println("show help: (TODO)")
	}
}
